package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.SupplierDao;
import com.huike.pmps.dao.SupplierSettlementDetailDao;
import com.huike.pmps.dao.SupplierWarehouseReceiptDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.*;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.POCourseService;
import com.huike.pmps.service.SupplierWarehouseReceiptService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Transactional
public class SupplierWarehouseReceiptServiceImpl implements SupplierWarehouseReceiptService {

    @Autowired
    SupplierSettlementDetailDao supplierSettlementDetailDao;

    @Autowired
    SupplierWarehouseReceiptDao supplierWarehouseReceiptDao;

    @Autowired
    SupplierDao supplierDao;

    @Autowired
    POCourseService poCourseService;

    /**
     * 入库生成入库单
     *
     * @param supplierWarehouseReceipt
     * @return
     */
    @Override
    public Result insertSupplierWarehouseReceipt(SupplierWarehouseReceipt supplierWarehouseReceipt) {
        if (supplierWarehouseReceipt != null && supplierWarehouseReceipt.getSupplierSettlementId() != null) {

            /**
             * todo 1. 新增入库单
             */
            //通过结算清单id获取结算清单详细信息
            SupplierSettlementDetail supplierSettlementDetail = supplierSettlementDetailDao.selectById(supplierWarehouseReceipt.getSupplierSettlementId());
            //将结算清单信息，拷贝给入库单
            BeanUtils.copyProperties(supplierSettlementDetail, supplierWarehouseReceipt, new String[]{"id", "rowEdit", "updateTime", "createTime", "state"});

            //查询课程，获取课程验收单
            POCourse poCourse = poCourseService.selectById(supplierSettlementDetail.getPoCourseId());
            if (poCourse != null) {
                //设置验收单路径
                supplierWarehouseReceipt.setSupplierInfoAcceptanceReportPath(poCourse.getAcceptanceReportPath());
            }
            //新增入库单
            supplierWarehouseReceiptDao.insert(supplierWarehouseReceipt);

            /**
             * todo 2. 更新结算单状态（已入库 state=1）
             */
            supplierSettlementDetail.setState(GlobalConstants.SUPPLIER_SETTLEMENT_STATE_IN);
            supplierSettlementDetail.setUpdateTime(new Date());
            supplierSettlementDetailDao.updateById(supplierSettlementDetail);
            /**
             * todo 3.更新供应商综合评级
             */
            Integer supplierId = supplierSettlementDetail.getSupplierId();
            //根据供应商supplierId获取供应商课程质量综合评分
            Double e1 = supplierWarehouseReceiptDao.selectSupplierEvaluation(supplierId);
            if (e1 != null) {
                //获取供应商初始评分
                Supplier supplier = supplierDao.selectById(supplierId);
                Double e2 = Double.valueOf(supplier.getInitEvaluation());
                supplier.setFinalEvaluation(e1 * 0.5 + e2 * 0.5);
                supplierDao.updateById(supplier);
            }
            /**
             * todo 4. 返回结果
             */
            return Result.success();
        } else {
            return Result.failure("结算清单ID为空，生成入库单失败");
        }
    }

    @Override
    public Result deleteById(Integer id) {
        SupplierWarehouseReceipt supplierWarehouseReceipt = supplierWarehouseReceiptDao.selectById(id);
        //结算清单ID
        Integer supplierSettlementId = supplierWarehouseReceipt.getSupplierSettlementId();
        //删除入库单
        if (supplierWarehouseReceiptDao.deleteById(id) > 0) {
            //更新结算清单ID
            SupplierSettlementDetail supplierSettlementDetail = SupplierSettlementDetail.builder().id(supplierSettlementId).state(GlobalConstants.SUPPLIER_SETTLEMENT_STATE_INIT).build();
            supplierSettlementDetailDao.updateById(supplierSettlementDetail);
            return Result.success();
        } else {
            return Result.failure("没有可删除的数据");
        }

    }


    @Override
    public Result selectByCondition(Member member, PageInfo pageInfo, String customerName, String supplierName, String courseChargeName,String courseName,Integer courseQualityEvaluation) {
        QueryWrapper<SupplierWarehouseReceipt> queryWrapper = new QueryWrapper<>();

        if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_ADMIN)) {//管理员
        } else if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_REGION)) {//战区司令
            if (member.getRegionId() == null) return Result.failure("您的账号没有配置所属战区，请联系 系统管理员 进行战区配置");
            queryWrapper.eq("region_id", member.getRegionId());
        } else {
            if (member.getProvinceId() == null) return Result.failure("您的账号没有配置所属省区，请联系 系统管理员 进行省区配置");
            queryWrapper.eq("province_id", member.getProvinceId());
        }

        if (StringUtils.isNotBlank(customerName))
            queryWrapper.like("customer_name", customerName);
        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);
        if (StringUtils.isNotBlank(courseChargeName))
            queryWrapper.like("course_charge_name", courseChargeName);

        if (StringUtils.isNotBlank(courseName))
            queryWrapper.like("course_name", courseName);
        if (courseQualityEvaluation!=null)
            queryWrapper.eq("course_quality_evaluation", courseQualityEvaluation);

        queryWrapper.orderByDesc("id");
        Page<SupplierWarehouseReceipt> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<SupplierWarehouseReceipt> pageList = supplierWarehouseReceiptDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }

    /**
     * 更新入库单 验收单路径
     *
     * @param acceptanceReportPath
     * @param poCourseId
     * @return
     */
    @Override
    public Result updateAcceptanceReportByPoCourseId(String acceptanceReportPath, Integer poCourseId) {
        supplierWarehouseReceiptDao.updateAcceptanceReportByPoCourseId(acceptanceReportPath, poCourseId);
        return Result.success();
    }

    @Override
    public void exportWarehouseReceipt(HttpServletResponse response, String customerName, String supplierName, String courseChargeName, Member member,String courseName,Integer courseQualityEvaluation) {
        QueryWrapper<SupplierWarehouseReceipt> queryWrapper = new QueryWrapper<>();

        /*if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_ADMIN)) {//管理员
        } else if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_REGION)) {//战区司令
            queryWrapper.eq("region_id", member.getRegionId());
        } else {
            queryWrapper.eq("province_id", member.getProvinceId());
        }*/

        if (StringUtils.isNotBlank(customerName))
            queryWrapper.like("customer_name", customerName);
        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);
        if (StringUtils.isNotBlank(courseChargeName))
            queryWrapper.like("course_charge_name", courseChargeName);

        if (StringUtils.isNotBlank(courseName))
            queryWrapper.like("course_name", courseName);
        if (courseQualityEvaluation!=null)
            queryWrapper.eq("course_quality_evaluation", courseQualityEvaluation);

        List<SupplierWarehouseReceipt> supplierWarehouseReceiptList = supplierWarehouseReceiptDao.selectList(queryWrapper);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("export_excel/warehouse_receipt_template.xlsx");
        XSSFWorkbook xssfWorkbook = null;
        try {

            xssfWorkbook = new XSSFWorkbook(in);
            //获取第一个工作表sheet
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            for (int i = 0; i < supplierWarehouseReceiptList.size(); i++) {
                SupplierWarehouseReceipt supplierWarehouseReceipt = supplierWarehouseReceiptList.get(i);
                XSSFRow row = sheetAt.createRow(i + 1);

                //课程ID
                XSSFCell courseIdCell = row.createCell(0);
                courseIdCell.setCellType(CellType.STRING);
                if (supplierWarehouseReceipt.getCourseId() != null)
                    courseIdCell.setCellValue(supplierWarehouseReceipt.getCourseId());

                //客户名称
                XSSFCell customerNameCell = row.createCell(1);
                customerNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getCustomerName()))
                    customerNameCell.setCellValue(supplierWarehouseReceipt.getCustomerName());

                //学科门类名称
                XSSFCell subjectCategoryNameCell = row.createCell(2);
                subjectCategoryNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getSubjectCategoryName()))
                    subjectCategoryNameCell.setCellValue(supplierWarehouseReceipt.getSubjectCategoryName());


                //省份名称
                XSSFCell provinceNameCell = row.createCell(3);
                provinceNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getProvinceName()))
                    provinceNameCell.setCellValue(supplierWarehouseReceipt.getProvinceName());


                //课程名称
                XSSFCell courseNameCell = row.createCell(4);
                courseNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getCourseName()))
                    courseNameCell.setCellValue(supplierWarehouseReceipt.getCourseName());

                //供应商名称
                XSSFCell supplierNameCell = row.createCell(5);
                supplierNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getSupplierName()))
                    supplierNameCell.setCellValue(supplierWarehouseReceipt.getSupplierName());

                //课程经理/课程编导
                XSSFCell courseChargeNameCell = row.createCell(6);
                courseChargeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getCourseChargeName()))
                    courseChargeNameCell.setCellValue(supplierWarehouseReceipt.getCourseChargeName());

                //拍摄形式名称
                XSSFCell shootModeNameCell = row.createCell(7);
                shootModeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplierWarehouseReceipt.getShootModeName()))
                    shootModeNameCell.setCellValue(supplierWarehouseReceipt.getShootModeName());

                //课程质量评分
                XSSFCell courseQualityEvaluationCell = row.createCell(8);
                courseQualityEvaluationCell.setCellType(CellType.STRING);
                if (supplierWarehouseReceipt.getCourseQualityEvaluation() != null)
                    courseQualityEvaluationCell.setCellValue(supplierWarehouseReceipt.getCourseQualityEvaluation());
            }
            String fileName = "warehouse_receipt_" + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + ".xlsx";
            response.setContentType("application/octet-stream"); // 响应内容格式
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public Result selectOneBySupplierSettlementId(Integer supplierSettlementId) {
        QueryWrapper<SupplierWarehouseReceipt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_settlement_id", supplierSettlementId);
        return Result.success(supplierWarehouseReceiptDao.selectOne(queryWrapper));
    }

    @Override
    public Result selectById(Integer id) {
        return Result.success(supplierWarehouseReceiptDao.selectById(id));
    }


}
